<template>
    <div id="index" style="background-color: #f4f4f4;width: 1519px;">
        <Layout>
            <Header style="background-color: white;width:100%;position: fixed;z-index: 2">
                <Menu mode="horizontal" theme="light" :active-name="1">
                    <MenuItem name="0" style="margin-right: 2%">
                        <div style="display: flex;align-items: center">
                            <img style="width: 50px" src="../assets/images/logo.png" alt="">
                            <img style="width: 180px;margin-left: 4%" src="../assets/images/logo2.png">
                        </div>
                    </MenuItem>
                    <MenuItem style="font-size: 16px" v-for="(nav,index) in navList" :key="index"
                              :name="nav.navId"
                              :to="nav.navUrl">
                        {{nav.navContent}}
                    </MenuItem>
                    <span v-if="userInfo.nickname==null||userInfo.nickname===''"
                          style="font-size: 18px;margin-left: 10%">
                    <a @click="$store.dispatch('showLogin')">登录</a> /
                    <a @click="registerVisable=true">注册</a>
                    </span>
                    <Submenu v-else
                             style="margin-left: 10%;"
                             name="-1">
                        <template slot="title">
                            <Badge :count="$store.state.informCount"></Badge>
                            <Avatar :src="userInfo.headPicture"/>
                            <span>{{userInfo.nickname}}</span>
                        </template>
                        <MenuItem name="2-1" to="/myIndex">我的主页</MenuItem>
                        <MenuItem name="2-2" @click.native="logout">退出登录</MenuItem>
                    </Submenu>
                </Menu>
            </Header>
            <Content style="margin: 5% auto 0 auto;width: 80%;z-index: 1">
                <router-view/>
            </Content>
            <Footer style="width:100%;margin-top: 2%;bottom: 0;display: flex;justify-content: center;align-items: center;background-color: white">
                <p>Copyright ©{{new Date().getFullYear()}} Edward | 备案号：皖ICP备20006135号-1</p>
            </Footer>
        </Layout>
        <!--登录页-->
        <Modal title="登录Edward博客" width="25" v-model="$store.state.loginVisable" footer-hide>
            <div class="pane-content">
                <div class="userpwd">
                    <img src="../assets/images/icon_people.png">
                    <input placeholder="请输入手机号" v-model="userVo.userPhone">
                </div>

                <div class="userpwd">
                    <img src="../assets/images/icon_password.png">
                    <input placeholder="请输入密码" type="password" v-model="userVo.password"
                           @keyup.enter="login">
                </div>

                <div class="setting">
                    <a href="#">七天内免登陆</a>
                    <a class="pull-right" @click="$store.dispatch('hideLogin');finPasswordVisable=true;">忘记密码?</a>
                </div>

                <button class="login-btn" @click="login">登&nbsp;录</button>

                <div class="reg">
                    还没账号?&nbsp;&nbsp;<a @click="$store.dispatch('hideLogin');registerVisable=true;">立即注册</a>
                </div>
            </div>
            <div class="pane-footer">
                <span>社交账号登录:  </span>
                <a @click="qqLogin"><img src="../assets/images/qq.png"></a>
                <a @click="$Modal.info({title:'提示',content:'目前只支持QQ三方登录!'})"><img src="../assets/images/weixin.png"></a>
                <a @click="$Modal.info({title:'提示',content:'目前只支持QQ三方登录!'})"><img src="../assets/images/sina.png"></a>
            </div>
            <div style="text-align: center;margin-top: 1%;color: #888888">请沿用之前的登录方式</div>
        </Modal>
        <!--注册页-->
        <Modal title="注册Edward博客" width="25" v-model="registerVisable" footer-hide>
            <div class="pane-content">
                <div class="userpwd">
                    <img src="../assets/images/icon_people.png">
                    <input placeholder="请输入手机号" v-model="registerVo.uPhone">
                </div>

                <div class="userpwd">
                    <img src="../assets/images/icon_password.png">
                    <input placeholder="请输入密码" type="password" v-model="registerVo.password">
                </div>
                <div class="userpwd">
                    <img src="../assets/images/icon_password.png">
                    <input placeholder="请再次输入密码" type="password" v-model="registerVo.uPassword">
                </div>

                <div style="display: flex;justify-content: space-between;margin-bottom: 4%">
                    <Input style="width: 48%" placeholder="请输入验证码" v-model="registerVo.code"
                           @keyup.native.enter="register"/>
                    <Button v-show="!timeButton" type="info" ghost @click="phoneCheck">发送验证码</Button>
                    <Button v-show="timeButton" disabled>{{leftTime}}秒后重新获取
                    </Button>
                </div>

                <div class="setting">
                    <a @click="registerVisable=false;finPasswordVisable=true;" class=" pull-right">忘记密码?</a>
                </div>

                <button class="login-btn" @click="register">注 册</button>

                <div class="reg">
                    已有账号?&nbsp;&nbsp;<a @click="registerVisable=false;$store.dispatch('showLogin')">立即登录</a>
                </div>
            </div>
        </Modal>
        <!--手机号找回密码-->
        <Modal title="找回Edward博客密码" width="25" v-model="finPasswordVisable" footer-hide>
            <div class="pane-content">
                <div class="userpwd">
                    <img src="../assets/images/icon_people.png">
                    <input placeholder="请输入手机号" v-model="findPwdVo.phone">
                </div>

                <div class="userpwd">
                    <img src="../assets/images/icon_password.png">
                    <input placeholder="请输入新密码" type="password" v-model="findPwdVo.password2">
                </div>
                <div class="userpwd">
                    <img src="../assets/images/icon_password.png">
                    <input placeholder="请再次输入新密码" type="password" v-model="findPwdVo.password">
                </div>

                <div style="display: flex;justify-content: space-between;margin-bottom: 4%">
                    <Input style="width: 48%" placeholder="请输入验证码" v-model="findPwdVo.code"
                           @keyup.native.enter="resetPwd"/>
                    <Button v-show="!timeButton2" type="info" ghost @click="resetPhone">发送验证码</Button>
                    <Button v-show="timeButton2" disabled>{{leftsecond}}秒后重新获取
                    </Button>
                </div>

                <button class="login-btn" @click="resetPwd">修 改</button>

                <div class="reg">
                    <div>已有账号?&nbsp;&nbsp;<a @click="finPasswordVisable=false;$store.dispatch('showLogin')">登录</a></div>
                    <div>没有账号? <a @click="finPasswordVisable=false;registerVisable=true;">注册</a></div>
                </div>
            </div>
        </Modal>
        <!--返回顶部-->
        <a>
            <div class="rightButton" style="bottom: 264px;border-bottom: 1px solid #888888" @click="adviceVisable=true">
                建议
            </div>
        </a>
        <a>
            <div class="rightButton" style="bottom: 223px;" @click="bugVisable=true">
                bug
            </div>
        </a>
        <BackTop :bottom="222">
            <div style="border-top: 1px solid #888888" class="rightButton">
                <Icon type="ios-arrow-up" color="red"/>
            </div>
        </BackTop>
        <!--添加功能建议对话框-->
        <Modal title="功能建议" v-model="adviceVisable" @on-ok="addArticle('adviceVoRef')"
               @on-cancel="adviceVisable=false">
            <Form ref="adviceVoRef" :model="adviceVo" :rules="adviceVoRules" :label-width="80">
                <FormItem label="标题：" prop="title">
                    <Input v-model="adviceVo.title" placeholder="请输入建议标题"/>
                </FormItem>
                <FormItem label="内容：" prop="content">
                    <Input v-model="adviceVo.content" type="textarea" placeholder="请输入建议详细内容" maxlength="250"
                           show-word-limit :rows="4"/>
                </FormItem>
            </Form>
        </Modal>
        <!--添加bug反馈-->
        <Modal title="BUG反馈" v-model="bugVisable" @on-ok="addBug('bugVoRef')"
               @on-cancel="bugVisable=false">
            <Form ref="bugVoRef" :model="bugVo" :rules="bugVoRules" :label-width="80">
                <FormItem label="内容：" prop="content">
                    <Input v-model="bugVo.content" type="textarea" placeholder="请输入建议详细内容" maxlength="250"
                           show-word-limit :rows="4"/>
                </FormItem>
            </Form>
        </Modal>
    </div>
</template>

<script>
  import '../assets/css/animate.css'
  import '../assets/css/index.css'

  export default {
    data () {
      return {
        searchTitle: '',
        // 控制登录弹出层的显示和异常
        registerVisable: false,
        finPasswordVisable: false,
        adviceVisable: false,
        bugVisable: false,
        // 控制倒计时按钮和点击按钮的切换
        timeButton: false,
        leftTime: 120,
        timeButton2: false,
        leftsecond: 120,
        userVo: {
          userPhone: '',
          password: ''
        },
        registerVo: {
          uPhone: '',
          password: '',
          uPassword: '',
          code: ''
        },
        findPwdVo: {
          password2: '',
          password: '',
          phone: '',
          code: ''
        },
        adviceVo: {
          title: '',
          content: ''
        },
        adviceVoRules: {
          title: [
            {
              required: true,
              message: '标题不能为空',
              trigger: 'blur'
            }
          ],
          content: [
            {
              required: true,
              message: '内容不能为空',
              trigger: 'blur'
            }
          ]
        },
        bugVo: {
          content: ''
        },
        bugVoRules: {
          content: [
            {
              required: true,
              message: '反馈内容补鞥你为空',
              trigger: 'blur'
            }
          ]
        },
        userInfo: {
          nickname: window.localStorage.getItem('nickname'),
          headPicture: window.localStorage.getItem('headPicture')
        },
        navList: []
      }
    },
    mounted () {
      this.getNavs()
      // vuex获取用户的消息通知
      this.$store.dispatch('informInfo', this)
    },
    methods: {
      getNavs () {
        this.$http.get('navs').then(res => {
          res = res.data
          if (res.code === 0) {
            this.navList = res.data
          } else {
            this.$Message.error(res.msg)
          }
        })
      },
      // 短信验证
      phoneCheck () {
        if (this.registerVo.uPhone === null || this.registerVo.uPhone === '') {
          this.$Message.error('手机号不能为空')
          return
        }
        if (!(/^1[3456789]\d{9}$/.test(this.registerVo.uPhone))) {
          this.$Message.error('手机号格式不正确，请输入正确的手机号')
          return
        }
        this.timeButton = true
        // 倒计时120s
        var that = this
        var myInterval = setInterval(function () {
          that.leftTime--
        }, 1000)
        setTimeout(function () {
          // 停止倒计时
          clearInterval(myInterval)
          // 初始化剩余时间
          that.leftTime = 120
          // 隐藏时间按钮
          that.timeButton = false
        }, 120000)
        // 发送请求
        this.$http.post(`register/${this.registerVo.uPhone}/0`).then(res => {
          res = res.data
          if (res.code === 1002) {
            this.$Message.success(res.msg)
          } else {
            this.$Message.error(res.msg)
          }
        })
      },
      // 注册
      register () {
        if (this.registerVo.uPhone === '' || this.registerVo.uPhone === null || this.registerVo.password === null || this.registerVo.password === '' || this.registerVo.uPassword === null || this.registerVo.uPassword === '') {
          this.$Message.error('手机号或密码不能为空')
          return
        }
        if (this.registerVo.code === null || this.registerVo.code === '') {
          this.$Message.error('验证码不能为空')
          return
        }
        if (this.registerVo.password !== this.registerVo.uPassword) {
          this.$Message.error('两次密码不一致，请重新输入')
          return
        }
        this.$http.post('register', new URLSearchParams(this.registerVo)).then(res => {
          res = res.data
          if (res.code === 2004) {
            this.$Message.success(res.msg)
            this.userVo.userPhone = this.registerVo.uPhone
            this.userVo.password = this.registerVo.password
            // 登录
            this.login()
          } else {
            this.$Message.error(res.msg)
          }
        })
      },
      // 重置密码短信验证
      resetPhone () {
        if (this.findPwdVo.phone === null || this.findPwdVo.phone === '') {
          this.$Message.error('手机号不能为空')
          return
        }
        if (!(/^1[3456789]\d{9}$/.test(this.findPwdVo.phone))) {
          this.$Message.error('手机号格式不正确，请输入正确的手机号')
          return
        }
        this.timeButton2 = true
        // 倒计时120s
        var that = this
        var myInterval = setInterval(function () {
          that.leftsecond--
        }, 1000)
        setTimeout(function () {
          // 停止倒计时
          clearInterval(myInterval)
          // 初始化剩余时间
          that.leftsecond = 120
          // 隐藏时间按钮
          that.timeButton2 = false
        }, 120000)
        // 发送请求
        this.$http.post(`register/${this.findPwdVo.phone}/1`).then(res => {
          res = res.data
          if (res.code === 1002) {
            this.$Message.success(res.msg)
          } else {
            this.$Message.error(res.msg)
          }
        })
      },
      // 重置密码
      resetPwd () {
        if (this.findPwdVo.phone === '' || this.findPwdVo.phone === null || this.findPwdVo.password === null || this.findPwdVo.password === '' || this.findPwdVo.password2 === null || this.findPwdVo.password2 === '') {
          this.$Message.error('手机号或密码不能为空')
          return
        }
        if (this.findPwdVo.code === null || this.findPwdVo.code === '') {
          this.$Message.error('验证码不能为空')
          return
        }
        if (this.findPwdVo.password !== this.findPwdVo.password2) {
          this.$Message.error('两次密码不一致，请重新输入')
          return
        }
        // 重置密码
        this.$http.put('register', new URLSearchParams(this.findPwdVo)).then(res => {
          res = res.data
          if (res.code === 2010) {
            this.$Message.success(res.msg)
            this.finPasswordVisable = false
            this.findPwdVo.phone = ''
            this.findPwdVo.password = ''
            this.findPwdVo.password2 = ''
            this.findPwdVo.code = ''
          } else {
            this.$Message.error(res.msg)
          }
        })
      },
      // 获取登录的用户信息
      getUserInfo (res) {
        // 查询登录的用户信息存入localStorage
        this.$http.get('user', {
          headers: {
            lhamster_identity_info: res.data.lhamster_identity_info
          }
        }).then(resp => {
          resp = resp.data
          if (resp.code === 0) {
            window.localStorage.setItem('nickname', resp.data.unickname)
            window.localStorage.setItem('headPicture', resp.data.uheadpicture)
            // 提示成功
            this.$Message.success(res.msg)
            this.$store.dispatch('hideLogin')
            // 登录输入框清空
            this.userVo.userPhone = ''
            this.userVo.password = ''
            // 重新加载当前路由
            location.reload()
          } else {
            this.$Message.error(resp.msg)
          }
        })
      },
      // 登录
      login () {
        if (this.userVo.userPhone === '' || this.userVo.userPhone === null || this.userVo.password === null || this.userVo.password === '') {
          this.$Message.error('手机号或密码不能为空')
          return
        }
        this.$http.post('login', new URLSearchParams(this.userVo)).then(res => {
          res = res.data
          if (res.code === 2000) {
            // 用户token存入localStorage
            window.localStorage.setItem('lhamster_identity_info', res.data.lhamster_identity_info)
            this.getUserInfo(res)
          } else {
            this.$Message.error(res.msg)
          }
        })
      },
      // 退出登录
      logout () {
        if (QC.Login.check()) {
          QC.Login.signOut()
        }
        window.localStorage.removeItem('lhamster_identity_info')
        window.localStorage.removeItem('nickname')
        window.localStorage.removeItem('headPicture')
        location.reload()
      },
      // QQ三方登录
      qqLogin () {
        // 直接弹出授权页面，授权过后跳转到回调页面进行登录处理
        QC.Login.showPopup({
          appId: '101892852',
          redirectURI: 'http://www.lhamster.cn/index.html'// 登录成功后会自动跳往该地址
        })
        this.sendMsg()
      },
      // 发送信息
      sendMsg () {
        // 检查是否登录
        var that = this
        if (QC.Login.check()) {
          // 将openid和accesstoken传递到后台
          QC.Login.getMe(function (openId, accessToken) {
            // 登录
            var params = new URLSearchParams()
            params.append('openId', openId)
            params.append('accessToken', accessToken)
            that.$http.post('qqLogin', params).then(res => {
              res = res.data
              if (res.code === 2000) {
                // 用户token存入localStorage
                window.localStorage.setItem('lhamster_identity_info', res.data.lhamster_identity_info)
                that.getUserInfo(res)
              } else {
                that.$Message.error(res.msg)
              }
            })
          })
        }
      },
      // 搜索框
      searchArticle () {
        console.log('searchTitle')
        console.log(this.searchTitle)
      },
      // 添加建议
      addArticle (name) {
        // 检验是否登录
        if (!window.localStorage.getItem('lhamster_identity_info')) {
          this.$store.dispatch('showLogin')
          this.$Message.info('请登录后再操作')
          return
        }
        this.$refs[name].validate(valid => {
          if (!valid) return
          // 发送请求
          this.$http.post('advice', new URLSearchParams(this.adviceVo)).then(res => {
            res = res.data
            if (res.code === 6801) {
              this.$refs[name].resetFields()
              // 更新通知
              this.$store.dispatch('informInfo', this)
              this.adviceVisable = false
              this.$Message.success('感谢您的建议，希望Edward博客越来越好~')
            } else {
              this.$Message.error(res.msg)
            }
          })
        })
      },
      // 添加bug反馈
      addBug (name) {
        // 检验是否登录
        if (!window.localStorage.getItem('lhamster_identity_info')) {
          this.$store.dispatch('showLogin')
          this.$Message.info('请登录后再操作')
          return
        }
        this.$refs[name].validate(valid => {
          if (!valid) return
          // 发送请求
          this.$http.post('bug', new URLSearchParams(this.bugVo)).then(res => {
            res = res.data
            if (res.code === 6901) {
              this.$refs[name].resetFields()
              // 更新通知
              this.$store.dispatch('informInfo', this)
              this.adviceVisable = false
              this.$Message.success('感谢您的BUG反馈，我会及时修改~')
            } else {
              this.$Message.error(res.msg)
            }
          })
        })
      }
    }
  }
</script>

<style scoped>
    #index {
        height: 100%;
        background-color: #f5f7f9;
    }

    .rightButton {
        background: white;
        position: fixed;
        width: 48px;
        height: 40px;
        right: 30px;
        display: flex;
        justify-content: center;
        align-items: center;
    }
</style>
